package com.allwinter.yibangsafe.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.allwinter.yibangsafe.domain.User;
import com.allwinter.yibangsafe.domain.WxUser;
import com.allwinter.yibangsafe.mapper.UserMapper;
import com.allwinter.yibangsafe.mapper.WxUserMapper;
import com.allwinter.yibangsafe.service.LoginService;
import com.allwinter.yibangsafe.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired(required = false)
    private WxUserMapper wxUserMapper;

    @Autowired(required = false)
    private UserMapper userMapper;

    @Value("${weixin.app.id}")
    private String appid;
    @Value("${weixin.app.secret}")
    private String secret;
    @Value("${weixin.app.code2Session}")
    private String Url_Session;

    /**
     * @param code:
     * @return JSONObject
     * @author 杨雪松
     * @description 通过前端code获取当前微信用户的openid
     * @date
     */
    @Override
    public JSONObject getSessionByCode(String code) {
        System.out.println("code: " + code);
        JSONObject result = new JSONObject();
        result.put("code",0);
        try{
            boolean check = (StringUtils.isEmpty(code)) ? true : false;
            if (check) {
                System.out.println("code: " + code);
                throw new Exception("参数异常");
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("appid",appid);
            jsonObject.put("secret",secret);
            jsonObject.put("js_code",code);
            jsonObject.put("grant_type","authorization_code");
            result = HttpClientUtils.httpGet(Url_Session, jsonObject);
        } catch (Exception e){
            result.put("code",1);
            result.put("remark",e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @param data:
     * @return JSONObject
     * @author 杨雪松
     * @description 解析微信用户信息，存储创建当前用户表
     * @date
     */
    @Override
    public JSONObject saveWxUserInfo(String data) {
        JSONObject msg = new JSONObject();
        JSONObject resmsg = JSONObject.parseObject(data);
        String wxUserInfoStr = resmsg.get("wxUserInfo").toString();
        String openid = resmsg.get("openid").toString();
        System.out.println("wxUserInfo: " + wxUserInfoStr);
        System.out.println("openid: " + openid);
        JSONObject wxUserInfo = JSON.parseObject(wxUserInfoStr);
        wxUserInfo.put("openid",openid);

        try {
            WxUser wxuserById = wxUserMapper.selectById(openid);
            if (wxuserById != null){
                msg.put("code",3);
                msg.put("userid",wxuserById.getUserid());
                msg.put("msg","用户已注册过");
            } else {
                //创建Userid
                Long userid = createUserid(openid);

                WxUser wxUser = new WxUser();
                wxUser.setAvatarurl(wxUserInfo.get("avatarUrl").toString());
                wxUser.setCity(wxUserInfo.get("city").toString() + ".");
                wxUser.setGender(wxUserInfo.get("gender").toString());
                wxUser.setUserid(userid);
                wxUser.setLanguage(wxUserInfo.get("language").toString());
                wxUser.setNickname(wxUserInfo.get("nickName").toString());
                wxUser.setOpenid(wxUserInfo.get("openid").toString());
                wxUser.setCountry(wxUserInfo.get("country").toString() + ".");
                wxUser.setProvince(wxUserInfo.get("province").toString() + ".");


                try {
                    //同时以userid为主键创建user信息
                    User user = new User();
                    user.setUserid(userid);
                    user.setImageaddress(wxUser.getAvatarurl());
                    user.setUsername(wxUser.getNickname());
                    user.setIsserver(0);
                    user.setPassword("DefaultPassword");
                    System.out.println("创建的User: " + user.toString());
                    userMapper.insert(user);
                    wxUserMapper.insert(wxUser);
                    System.out.println("创建的wxUser：" + wxUser.toString());
                    msg.put("code",1);
                    msg.put("userid",userid);
                    msg.put("msg","save success");
                } catch (Exception e) {
                    msg.put("code",0);
                    msg.put("msg","save fails");
                    msg.put("errorinfo",e.toString());
                    e.printStackTrace();
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return msg;
    }

    public Long createUserid(String openid){
        Long res = null;
        String temp = "";
        if (openid != null && !"".equals(openid)) {
            for (int i = 0; i < openid.length(); i++) {
                if (openid.charAt(i) >= 48 && openid.charAt(i) <= 57) {
                    temp += openid.charAt(i);
                }
            }
        }
        res = Long.parseLong(temp);
        return res;
    }




}
